<template>
  <el-dialog
    title="修改入库单"
    :visible.sync="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form :model="form" :rules="rules" ref="editForm" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入库单号" prop="boundCode">
            <el-input v-model="form.boundCode" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="制单人" prop="creator">
            <el-input v-model="form.creator" placeholder="请输入制单人"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="单据日期" prop="createTime">
            <el-date-picker
              v-model="form.createTime"
              type="date"
              placeholder="请选择时间"
              style="width: 100%"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="form.supplierId" placeholder="请选择供应商" style="width: 100%">
              <el-option
                v-for="supplier in suppliers"
                :key="supplier.supplierId"
                :label="supplier.supplierName"
                :value="supplier.supplierId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入库仓库" prop="warehouseId">
            <el-select v-model="form.warehouseId" placeholder="请选择仓库" style="width: 100%">
              <el-option
                v-for="warehouse in warehouses"
                :key="warehouse.warehouseId"
                :label="warehouse.warehouseName"
                :value="warehouse.warehouseId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="操作状态" prop="boundStatus">
            <el-select v-model="form.boundStatus" placeholder="请选择状态" style="width: 100%">
              <el-option label="入库" :value="1"></el-option>
              <el-option label="出库" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="小区" prop="communityId">
            <el-select v-model="form.communityId" placeholder="请选择小区" style="width: 100%">
              <el-option
                v-for="community in communities"
                :key="community.communityId"
                :label="community.communityName"
                :value="community.communityId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注信息" type="textarea" :rows="3"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { boundApi } from '@/api/bound'
import { supplierApi } from '@/api/supplier'
import { warehouseApi } from '@/api/warehouse'

export default {
  name: 'EditBoundDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    boundId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      dialogVisible: false,
      submitting: false,
      suppliers: [],
      warehouses: [],
      communities: [],
      boundInfoList: [], // 存储入库单详情列表
      form: {
        boundCode: '',
        creator: '',
        createTime: '',
        supplierId: '',
        warehouseId: '',
        communityId: '',
        boundStatus: 1,
        remark: ''
      },
      rules: {
        creator: [
          { required: true, message: '请输入制单人', trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '请选择单据日期', trigger: 'change' }
        ],
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        warehouseId: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        boundStatus: [
          { required: true, message: '请选择操作状态', trigger: 'change' }
        ],
        communityId: [
          { required: true, message: '请选择小区', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.dialogVisible = newVal
        if (newVal && this.boundId) {
          this.loadBoundDetail()
        }
      },
      immediate: true
    },
    dialogVisible(newVal) {
      this.$emit('update:visible', newVal)
    }
  },
  created() {
    this.loadSuppliers()
    this.loadWarehouses()
    this.loadCommunities()
  },
  methods: {
    // 加载供应商列表
    async loadSuppliers() {
      try {
        const response = await supplierApi.getAllSuppliers()
        if (response.code === 200) {
          this.suppliers = response.data || []
        }
      } catch (error) {
        console.error('加载供应商列表失败:', error)
      }
    },

    // 加载仓库列表
    async loadWarehouses() {
      try {
        const response = await warehouseApi.getAllWarehouses()
        if (response.code === 200) {
          this.warehouses = response.data || []
        }
      } catch (error) {
        console.error('加载仓库列表失败:', error)
      }
    },

    // 加载小区列表
    async loadCommunities() {
      try {
        const response = await warehouseApi.getAllCommunities()
        if (response.code === 200) {
          this.communities = response.data || []
        }
      } catch (error) {
        console.error('加载小区列表失败:', error)
      }
    },

    // 加载入库单详情
    async loadBoundDetail() {
      try {
        const response = await boundApi.getBoundById(this.boundId)
        if (response.code === 200) {
          const data = response.data
          this.form = {
            boundCode: data.boundCode || '',
            creator: data.creator || '',
            createTime: data.creatorTime || '',
            supplierId: data.supplierId || '',
            warehouseId: data.warehouseId || '',
            communityId: data.communityId || '',
            boundStatus: data.boundStatus || 1,
            remark: data.boundDesc || ''
          }
          // 加载入库单详情列表
          this.boundInfoList = data.boundInfoList || []
        } else {
          this.$message.error(response.message || '加载入库单详情失败')
        }
      } catch (error) {
        console.error('加载入库单详情失败:', error)
        this.$message.error('加载入库单详情失败，请稍后重试')
      }
    },

    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.editForm.validate()
        
        this.submitting = true

        const formData = {
          boundId: this.boundId,
          boundCode: this.form.boundCode,
          creator: this.form.creator,
          createTime: this.form.createTime,
          supplierId: this.form.supplierId,
          warehouseId: this.form.warehouseId,
          communityId: this.form.communityId,
          boundStatus: this.form.boundStatus,
          boundDesc: this.form.remark
        }

        const response = await boundApi.updateBoundBasic(formData)
        if (response.code === 200) {
          this.$message.success('修改成功')
          this.$emit('success')
          this.handleClose()
        } else {
          this.$message.error(response.message || '修改失败')
        }
      } catch (error) {
        console.error('修改失败:', error)
        this.$message.error('修改失败，请稍后重试')
      } finally {
        this.submitting = false
      }
    },

    // 取消
    handleCancel() {
      this.handleClose()
    },

    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false
      this.resetForm()
    },

    // 重置表单
    resetForm() {
      this.form = {
        boundCode: '',
        creator: '',
        createTime: '',
        supplierId: '',
        warehouseId: '',
        communityId: '',
        boundStatus: 1,
        remark: ''
      }
      this.boundInfoList = []
      if (this.$refs.editForm) {
        this.$refs.editForm.clearValidate()
      }
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input,
.el-select,
.el-date-picker {
  width: 100%;
}

.el-textarea {
  width: 100%;
}

/* 弹窗样式优化 */
.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  border-radius: 8px 8px 0 0;
  padding: 20px 20px 15px;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  background-color: #f5f7fa;
  border-top: 1px solid #e4e7ed;
  border-radius: 0 0 8px 8px;
  padding: 15px 20px 20px;
}

/* 表单样式 */
.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-input__inner,
.el-textarea__inner {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.el-input__inner:focus,
.el-textarea__inner:focus {
  border-color: #409eff;
}

.el-select .el-input__inner {
  cursor: pointer;
}

/* 按钮样式 */
.el-button {
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button--primary:disabled {
  background-color: #c0c4cc;
  border-color: #c0c4cc;
}
</style>
